package com.UnionPayCenter.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.UnionPayCenter.entity.ResponseWrapper;
import com.UnionPayCenter.entity.WhiteListEntity;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.exception.ApiException;
import com.UnionPayCenter.jwt.CurrentManager;
import com.UnionPayCenter.jwt.CurrentShop;
import com.UnionPayCenter.jwt.RedisTokenManager;
import com.UnionPayCenter.jwt.TokenEntity;
import com.UnionPayCenter.service.IWhiteListService;
import com.UnionPayCenter.swagger.ApiJsonObject;
import com.UnionPayCenter.swagger.ApiJsonProperty;
import com.UnionPayCenter.util.PhoneCheckUtil;
import com.UnionPayCenter.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: UnionPayCenter
 * @description:
 * @author BaoJF
 *
 */
@Slf4j
@Api(value = "whiteList", tags = "白名单")
@RestController
@RequestMapping("/whiteList")
public class WhiteListController {
    @Autowired
    private IWhiteListService whiteListService;
    @Autowired
    private RedisTokenManager tokenManager;
    
    @CurrentShop
    @CurrentManager
    @RequestMapping(value = "/findList", method = RequestMethod.POST)
    @ApiOperation(tags = "白名单", httpMethod = "POST", value = "[后台]查询白名单列表", response = WhiteListEntity.class)
    public ResponseWrapper findList(
            @ApiJsonObject(name = "whitelistFindListParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "page", value = "页数", type = "int", required = false),
                    @ApiJsonProperty(key = "pageSize", value = "每页条数", type = "int", required = false),
                    @ApiJsonProperty(key = "mobile", value = "手机号筛选", required = false)
            })@RequestBody JSONObject jsonParam) {
        try {
            Integer managerId = jsonParam.getInteger("managerId");
            if (managerId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW100);
            }
            PageInfo<WhiteListEntity> list = whiteListService.findList(jsonParam);
            return ResponseWrapper.succeed(list);
        }catch (ApiException e){
            log.error(String.format("[后台]查询白名单列表失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]查询白名单列表失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }
    
    @CurrentShop
    @CurrentManager
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(tags = "白名单", httpMethod = "POST", value = "[后台]添加白名单", response = String.class)
    public ResponseWrapper add(
            @ApiJsonObject(name = "whitelistAddParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "mobile", value = "手机号")
            })@RequestBody JSONObject jsonParam) {
        try {
            Integer managerId = jsonParam.getInteger("managerId");
            String mobile = jsonParam.getString("mobile");
            if (managerId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW100);
            }
            if (StringUtils.isNullStr(mobile)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "mobile"));
            }
            if (!PhoneCheckUtil.isPhoneLegal(mobile)) {
                return ResponseWrapper.failed(ErrorCodeEnum.FL500.code(), String.format(ErrorCodeEnum.FL500.msg().concat("[%s]"), "手机号不规范"));
            }
            whiteListService.add(jsonParam);
            return ResponseWrapper.succeed("添加成功");
        }catch (ApiException e){
            log.error(String.format("[后台]添加白名单失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]添加白名单失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }
    
    @CurrentShop
    @CurrentManager
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ApiOperation(tags = "白名单", httpMethod = "POST", value = "[后台]删除白名单", response = String.class)
    public ResponseWrapper delete(
            @ApiJsonObject(name = "whitelistDeleteParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "wlId", value = "白名单id", type = "int")
            })@RequestBody JSONObject jsonParam) {
        try {
            Integer managerId = jsonParam.getInteger("managerId");
            String wlId = jsonParam.getString("wlId");
            if (managerId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW100);
            }
            if (StringUtils.isNullStr(wlId)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "wlId"));
            }
            if (!StringUtils.isNumeric(wlId)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "wlId"));
            }
            whiteListService.delete(jsonParam);
            return ResponseWrapper.succeed("删除成功");
        }catch (ApiException e){
            log.error(String.format("[后台]删除白名单失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]删除白名单失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }
    
    @CurrentShop
    @CurrentManager
    @RequestMapping(value = "/exportModel", method = RequestMethod.POST)
    @ApiOperation(tags = "白名单", httpMethod = "POST", value = "[后台]白名单导入模版下载", response = String.class)
    public ResponseWrapper exportModel(
            @ApiJsonObject(name = "whitelistExportModelParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int")
            })@RequestBody JSONObject jsonParam) {
        try {
            Integer managerId = jsonParam.getInteger("managerId");
            if (managerId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW100);
            }
            String url = whiteListService.exportModel(jsonParam);
            return ResponseWrapper.succeed(url);
        }catch (ApiException e){
            log.error(String.format("[后台]白名单导入模版下载失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]白名单导入模版下载失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }
    
    @RequestMapping(value = "/importWhitelist", method = RequestMethod.POST)
    @ApiOperation(tags = "白名单", httpMethod = "POST", value = "[后台]白名单导入", response = WhiteListEntity.class)
    public ResponseWrapper importWhitelist(@RequestParam(value = "token") String token, @RequestParam(value = "shopId") Integer shopId, @RequestParam(value = "file") MultipartFile file) {
        try {
            TokenEntity tokenEntity = tokenManager.getToken(token);
            Integer managerId = tokenEntity.getUserId();
            if (managerId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW100);
            }

            List<WhiteListEntity> list = whiteListService.importWhiteList(managerId, shopId, file);
            return ResponseWrapper.succeed(list);
        }catch (ApiException e){
            log.error(String.format("[后台]白名单导入失败，shopId:%s, 错误信息:%s", shopId, e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]白名单导入失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }
    
    @CurrentShop
    @CurrentManager
    @RequestMapping(value = "/setWhitelist", method = RequestMethod.POST)
    @ApiOperation(tags = "白名单", httpMethod = "POST", value = "[后台]白名单设置", response = String.class)
    public ResponseWrapper setWhitelist(
            @ApiJsonObject(name = "setWhitelistParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "levelId", value = "会员等级id", type = "int"),
                    @ApiJsonProperty(key = "couponList", value = "优惠券list")
            })@RequestBody JSONObject jsonParam) {
        try {
            Integer managerId = jsonParam.getInteger("managerId");
            if (managerId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW100);
            }
            whiteListService.setWhitelist(jsonParam);
            return ResponseWrapper.succeed("设置成功");
        }catch (ApiException e){
            log.error(String.format("[后台]白名单设置失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]白名单设置失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }
    
    @CurrentShop
    @CurrentManager
    @RequestMapping(value = "/findSetInfo", method = RequestMethod.POST)
    @ApiOperation(tags = "白名单", httpMethod = "POST", value = "[后台]查询白名单设置", response = Map.class)
    public ResponseWrapper findSetInfo(
            @ApiJsonObject(name = "findSetInfoParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int")
            })@RequestBody JSONObject jsonParam) {
        try {
            Integer managerId = jsonParam.getInteger("managerId");
            if (managerId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW100);
            }
            Map<String, Object> result = whiteListService.findSetInfo(jsonParam);
            return ResponseWrapper.succeed(result);
        }catch (ApiException e){
            log.error(String.format("[后台]查询白名单设置失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]查询白名单设置失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }
}
